/**
 *
 */

var getJsMindData = function () {
    //var jm = jsMind.current;
    deleteAllNode();
    jm.enable_edit();
    // 先删除现有的node
    $.getJSON(
        "/memorypalace/knowledge/getknowledgetree.action",
        function (json) {
            $.each(json, function (i, obj) {
                console.log(obj);
                // 如果类型为节点
                if (obj.data.type == 1 && obj.id != "root") {
                    jm.add_node(jm.get_node(obj.parentid), obj.id, obj.topic, obj.data);
                }
                // 如果有子笔记
                var arrayLength;
                try {
                    arrayLength = obj.data.notes.length;
                }catch (err){

                }
                if (arrayLength != 0 && arrayLength != undefined) {
                    $.each(obj.data.notes, function (i, noteNode) {
                        // noteNode 笔记节点 笔记的nodeid的结构是fatherKnowledgeTreeId:noteId
                        jm.add_node(jm.get_node(obj.id), noteNode.id, noteNode.topic, noteNode.data);
                        var node = $("jmnode[nodeId='" + noteNode.id + "']").attr({"type": "note"});
                        node.trigger("create");
                        console.log(node);
                    })
                    console.log("有笔记");
                    jm.collapse_node(obj.id);
                }

            });

            jm.disable_edit();
        }
    );
};

var knowledgeNameOnChange = function (str) {
    if (str.trim() == "") {
        $("#HCloseBtn").removeClass("HCloseBtn");
        console.log("remove");
        // $("#HCloseBtn").off();
        // $("#HCloseBtn").on('click',toaddKnowledge);
    } else {
        $("#HCloseBtn").addClass("HCloseBtn");
        console.log("add");
        // $("#HCloseBtn").off();
        // $("#HCloseBtn").on('click',toaddKnowledge);
        // $("#HCloseBtn").on('click',function () {
        //     //$.methods.close()
        // });
    }

}
// 表格
var defaultIndex = ['index', 'deckName', 'noteTitle', 'noteTypeName', 'noteCreateTime', 'noteEditTime']
var reference = {
    'deckName': 'deck.deckName',
    'noteTypeName': 'noteType.noteTypeName',
    'noteTitle': 'noteTitle',
    'noteCreateTime': 'noteCreateTime',
    'noteEditTime': 'noteEditTime'
};
var tableMaxWidth = {
    'index': '52',
    'deckName': '80',
    'noteTitle': '150',
    'noteTypeName': '112',
    'noteCreateTime': '140',
    'noteEditTime': '140'
}
var chineseRefer = {
    'index': '序号',
    'deckName': '牌组名称',
    'noteTypeName': '笔记类型名称',
    'areaContents': '区域内容',
    'noteTitle': '笔记标题',
    'noteCreateTime': '笔记创建时间',
    'noteEditTime': '笔记修改时间'
};
var _curPage = 1;//当前页数
var _pageCount = 10;//每页显示个数
var addTableTH = function () {
    var s = JSON.stringify(defaultIndex);

    $('.mytable').html('');
    lineNum = (_curPage - 1) * _pageCount;
    var h = '<tr>';
    for (var i = 0; i < defaultIndex.length; i++) {
        var title = chineseRefer[defaultIndex[i]];
        if (defaultIndex[i] == "index") {
            h += '<th>';
            h += "<button type='button' class='btn btn-default bordernone'" +
                " aria-haspopup='true' aria-expanded='false'>" + title;
            h += '</button></th>';
        } else {
            h += '<th>';
            h += "<button type='button' class='btn btn-default bordernone'" +
                " aria-haspopup='true' onclick='' aria-expanded='false'>" + title;
            if (defaultIndex[i] != 'index') {
                h += "<span class='caret'  style='margin-left:0.5em'></span> </button>";
            }
            h += '</th>';
        }
    }
    h += '</tr>';
    $('.mytable').append(
        h
    );
};
var lineNum = 0;
var addTableTD = function (note) {
    var h = "";
    if (noteChoosed.indexOf(note.noteId) != -1) {
        // 已选中该笔记
        h += '<tr id="' + note.noteId + '" class="trChoosed">';
    } else {
        // 如果不存在
        h += '<tr id="' + note.noteId + '">';
    }
    for (var i = 0; i < defaultIndex.length; i++) {
        var value;
        if (defaultIndex[i] == 'index') {
            value = ++lineNum;
        } else {
            var refer = reference[defaultIndex[i]];//deck.deckName
            if (refer == 'noteTitle') {
                // var titleKey = JSON.parse(note.areaNames)[0]; //正面
                var json = JSON.parse(note.areaContents);// 数组
                var titleValue = json[0];
                value = titleValue;
            } else {
                // 直接通过属性获取到
                if (refer.split('.').length == 1) {
                    value = note[refer.split('.')[0]];
                } else {
                    value = note[refer.split('.')[0]][refer.split('.')[1]];
                }
                if (defaultIndex[i].indexOf("Time") != -1) {
                    // noteCreateTime
                    var mydate = new Date(value);
                    value = mydate.toString();
                }
            }
        }
        var maxWidth = tableMaxWidth[defaultIndex[i]];
        h += '<td>';
        h += "<div style='max-width: " + maxWidth + "px'>" + value + "</div>";
        h += '</td>';
    }
    h += '</tr>';
    $('.mytable').append(
        h
    );
    $(".mytable tr:not(:first-child)").off();
    $(".mytable tr:not(:first-child)").on('click', chooseNote)
        .hover(function () {
                $(this).addClass("trHover");
            },
            function () {
                $(this).removeClass("trHover");
            });

};
var noteChoosed = new Array();
var setNoteChoosed = function (array) {
    noteChoosed = array;
    $("#selectedCount").html(noteChoosed.length);
}

var chooseNote = function (event) {
    var tr = event.delegateTarget;
    $(tr).toggleClass("trChoosed");
    $(tr).toggleClass("trHover");
    console.log($(tr));
    var id = $(tr).attr("id");
    var index = noteChoosed.indexOf(id);
    if (index == -1) {
        // 不存在其中, 第一次点击
        noteChoosed.push(id);
    } else {
        noteChoosed.splice(index, 1);//删除掉它
    }
    // 显示已选中
    $("#selectedCount").html(noteChoosed.length);
};


// 第一个参数是已选中的note数组,第二个参数是当前浏览的卡片
var setTableData = function (selectedNotes, notesInDeck) {
    if (selectedNotes != undefined) {
        // 已选中的数组改变
        setNoteChoosed(selectedNotes);
    } else {
        // 标题
        addTableTH();
        // 新增知识体系
        $.each(notesInDeck, function (i, noteInDeck) {
            addTableTD(noteInDeck);
        })
    }

    $("#knowledgeHBox").removeClass('btn btn-default');
}

// 如果传一个undefine则为获取所有牌组的笔记,isfromA如果有值代表这是从分页按钮上点过来的,然后赋予一个deckId
var getTableDataByDeck = function (deckId, curPage, isfromA) {
    if (isfromA != undefined) {
        deckId = $("#noteInDeckId").val()
    }
    if (deckId == undefined) {
        deckId = "";
    }
    if (curPage == undefined) {
        curPage = 1
    }
    var searchText = "";
    if ($("#searchTextInput").val().trim().length>0) {
        searchText = $("#searchTextInput").val().trim();
    }
    // 拿到所有牌组的noteInDeck
    $.getJSON(
        "/memorypalace/knowledge/toaddknowledgetree.action?deckId=" + deckId + "&curPage=" + curPage + "&searchText=" + searchText,
        function (notesInPage) {
            // 显示总数
            $("#totalCount").html(notesInPage.recordNum);
            // 显示分页导航
            _curPage = curPage;//影响分页之后的序号问题
            $("#pageNav").html("");
            // 首页
            var h = '<li>' +
                '<a href="javascript:getTableDataByDeck(undefined,1,1)" aria-label="Previous">' +
                '<span aria-hidden="true">&laquo;</span>' +
                '</a>' +
                '</li>';
            if (notesInPage.totalPage <= 5) {
                // 如果是小于等于5,不需要缩略的情况
                for (var i = 1; i <= notesInPage.totalPage; i++) {
                    if (i != curPage) {
                        h += '<li><a href="javascript:getTableDataByDeck(undefined,' + i + ',1)">' + i + '</a></li>';
                    } else {//class="active"
                        h += '<li class="active"><a href="javascript:getTableDataByDeck(undefined,' + i + ',1)">' + i + '</a></li>';
                    }
                }
            } else {
                var low = curPage - 2;
                var hight = curPage + 2;
                if (curPage <= 2) {
                    low = 1;
                    hight = 5;
                }
                if (curPage >= notesInPage.totalPage - 2) {
                    hight = notesInPage.totalPage;
                    low = notesInPage.totalPage - 4;
                }
                for (var i = low; i <= hight; i++) {
                    var content = i;
                    if (i == low) {
                        content = "..." + i;
                    }
                    if (i == hight) {
                        content = i + "...";
                    }
                    if (i != curPage) {
                        h += '<li><a href="javascript:getTableDataByDeck(undefined,' + i + ',1)">' + content + '</a></li>';
                    } else {//class="active"
                        h += '<li class="active"><a href="javascript:getTableDataByDeck(undefined,' + i + ',1)">' + content + '</a></li>';
                    }
                }
            }
            // 尾页
            h += '<li>' +
                '<a href="javascript:getTableDataByDeck(undefined,' + notesInPage.totalPage + ',1)"' +
                ' aria-label="Previous">' +
                '<span aria-hidden="true">&raquo;</span>' +
                '</a>' +
                '</li>';
            if (notesInPage.totalPage == 0) {
                h = '';
            }
            $("#pageNav").html(h);
            // 第一个参数是已选中的note数组,第二个参数是当前浏览的卡片
            setTableData(undefined, notesInPage.data);
        }
    );

};

// --------------------表格结束
// --------------------弹窗开始
var clickaddKnowledge = function () {
    showDialog(true);
}
var clickeditKnowledge = function () {
    var nodeId = $(".selected").attr('nodeId');
    // 如果没有选中的node,或者选中的nodeid是笔记的nodeid,则返回错误
    if (nodeId == null) {
        console.log("没有选中一个知识体系!");
        showTip('请选中一个知识体系', 1000);
    } else {
        if(nodeId == "root"){
            showTip('请选中非根节点的知识体系', 1000);
        }else {
            // 如果选中了,但是选中的nodeid是笔记的nodeid
            if (nodeId.split(':').length > 1) {
                var noteId = nodeId.split(":")[1];
                // showEditNote(noteId);
                showTip('请选中一个知识体系', 1000);
            } else {
                console.log(nodeId);
                showDialog(false, nodeId);
            }
        }
    }
}
// 设置数据
var beforeaddKnowledge = function () {
    var nodeId = "";

    // 选择知识体系,并且更新"父级知识体系"的下拉菜单
    $.getJSON(
        "/memorypalace/knowledge/getknowledgetree.action",
        function (json) {
            var isFirstAddFather = true;
            $("#knowledgeFatherIdList").html('');
            $.each(json, function (i, obj) {
                if (obj.data.type == 1) {
                    if (isFirstAddFather) {
                        isFirstAddFather = false;
                        // 解析knowledgeTree
                        $("#knowledgeFatherId").html(obj.topic + '<span class="caret" style="margin-left:0.5em"></span>');
                        $("#knowledgeFatherId").val(obj.id);
                    }
                    console.log("添加" + obj.topic)
                    $("#knowledgeFatherIdList").append(
                        "<li><a href=\"javascript:changeDropDownBtnValue('" + obj.topic + "','knowledgeFatherId','" + obj.id + "')\">" + obj.topic + "</a></li>"
                    );
                    $("#knowledgeFatherIdList").val(obj.id);
                }
            });
        }
    );
    // 选择卡片,更新"下拉菜单"
    $("#noteInDeckId").html('所有牌组<span class="caret" style="margin-left:0.5em"></span>');
    $.getJSON(
        "/memorypalace/knowledge/getmydeck.action",
        function (deckList) {
            // 初始化
            $("#noteInDeckIdList").html('');
            // 下拉中的"所有牌组"
            $("#noteInDeckIdList").append(
                "<li><a href=\"javascript:changeDropDownBtnValue('所有牌组','noteInDeckId','');" +
                "getTableDataByDeck()\">所有牌组</a></li>"
            );
            $.each(deckList, function (i, deck) {
                $("#noteInDeckIdList").append(
                    "<li><a href=\"javascript:changeDropDownBtnValue('" + deck.deckName + "','noteInDeckId','" + deck.deckId + "');" +
                    "getTableDataByDeck('" + deck.deckId + "')\">" + deck.deckName + "</a></li>"
                );
            });
        }
    );
    setNoteChoosed(new Array());
    // 获取表格的数据,并且设置数据,不传变量意为找所有牌组
    getTableDataByDeck();


    // 确定按钮触发事件绑定
    $("#HCloseBtn").off();
    $("#HCloseBtn").on("click", toaddKnowledge);

    // 类型选择初始化
    $("#knowledgeType").html('节点<span class="caret" style="margin-left:0.5em"></span>');
    $("#knowledgeType").val(1);


};
var knowledgeTypeMap = {
    1: '节点',
    2: '集合',
    3: '序列',
    4: '有向图'
};
var beforeeditKnowledge = function () {
    var nodeId = $("#knowledgeId").val();
    // 解析knowledgeTree,设置当前的名称,类型,父级知识体系
    $.getJSON(
        "/memorypalace/knowledge/toeditknowledgetree.action?knowledgeTreeId=" + nodeId,
        function (json) {
            $("#knowledgeName").val(json.knowledgeName);
            $("#knowledgeType").html(knowledgeTypeMap[json.knowledgeType] + '<span class="caret" style="margin-left:0.5em"></span>');
            $("#knowledgeType").val(json.knowledgeType);
            if (json.fatherKnowledgeTree != undefined) {
                $("#knowledgeFatherId").html(json.fatherKnowledgeTree.knowledgeName + '<span class="caret" style="margin-left:0.5em"></span>');
                $("#knowledgeFatherId").val(json.fatherKnowledgeTree.knowledgeId);
            } else {
                $("#knowledgeFatherId").html('我的知识体系' + '<span class="caret" style="margin-left:0.5em"></span>');
                $("#knowledgeFatherId").val('root');
            }
            console.log("数组");
            console.log(json.noteList);
            var n = new Array();
            $.each(json.noteList, function (i, note) {
                n.push(note.noteId);
            });
            setNoteChoosed(n);
            getTableDataByDeck();
        }
    );
    // 选择除自己以外的知识体系,并且更新"父级知识体系"的下拉菜单
    $.getJSON(
        "/memorypalace/knowledge/getknowledgetree.action?knowledgeId="+nodeId,
        function (json) {
            $("#knowledgeFatherIdList").html('');
            $.each(json, function (i, obj) {
                if (obj.data.type == 1 && obj.id != nodeId) {
                    console.log("添加" + obj.topic)
                    $("#knowledgeFatherIdList").append(
                        "<li><a href=\"javascript:changeDropDownBtnValue('" + obj.topic + "','knowledgeFatherId','" + obj.id + "')\">" + obj.topic + "</a></li>"
                    );

                    $("#knowledgeFatherIdList").val(obj.id);
                }
            });
        }
    );
    // 选择卡片,更新所有牌组"下拉菜单"
    $("#noteInDeckId").html('所有牌组<span class="caret" style="margin-left:0.5em"></span>');
    $.getJSON(
        "/memorypalace/knowledge/getmydeck.action",
        function (deckList) {
            // 初始化
            $("#noteInDeckIdList").html('');
            // 下拉中的"所有牌组"
            $("#noteInDeckIdList").append(
                "<li><a href=\"javascript:changeDropDownBtnValue('所有牌组','noteInDeckId','');" +
                "getTableDataByDeck()\">所有牌组</a></li>"
            );
            $.each(deckList, function (i, deck) {
                $("#noteInDeckIdList").append(
                    "<li><a href=\"javascript:changeDropDownBtnValue('" + deck.deckName + "','noteInDeckId','" + deck.deckId + "');" +
                    "getTableDataByDeck('" + deck.deckId + "')\">" + deck.deckName + "</a></li>"
                );
            });
        }
    );
    // 获取表格的数据,并且设置数据,不传变量意为找所有牌组,(这里注释掉,在获取到已选择的noteId后执行)
    //getTableDataByDeck();

    // 确定按钮触发事件绑定
    $("#HCloseBtn").off();
    $("#HCloseBtn").on("click", toeditKnowledge);

    // 标题更改
    $("#knowledgeHBox>form>h2").html("编辑知识体系");
};
// isAdd 表明要显示一个add 弹窗
var showDialog = function (isAdd, nodeId) {
    if (isAdd) {
        $("#addKnowledgeHBoxBtn").hDialog({
            box: '#knowledgeHBox',
            closeHide: false,
            width: 840,
            height: 700,
            beforeShow: function () {
                beforeaddKnowledge();
            },
            afterHide: function () {
                $("#addKnowledgeHBoxBtn").off();
                $("#addKnowledgeHBoxBtn").on('click', clickaddKnowledge)
            }
        });
    } else {
        $("#knowledgeId").val(nodeId);
        $("#editKnowledgeHBoxBtn").hDialog({
            box: '#knowledgeHBox',
            closeHide: false,
            width: 840,
            height: 700,
            beforeShow: function () {
                beforeeditKnowledge();
            },
            afterHide: function () {
                $("#editKnowledgeHBoxBtn").off();
                $("#editKnowledgeHBoxBtn").on('click', clickeditKnowledge);
            }
        });
    }
}

var showEditNote = function (noteId) {
    $("#noteId").val(noteId);
    $("#editKnowledgeHBoxBtn").hDialog({
        box: '#editNoteHBox',
        closeHide: false,
        width: 840,
        height: 700,
        beforeShow: function () {
            setTimeout(function () {
                $("#editNoteHBox").removeClass('btn btn-default');
            }, 100);

            beforeeditNote();
        },
        afterHide: function () {
            $("#editKnowledgeHBoxBtn").off();
            $("#editKnowledgeHBoxBtn").on('click', clickeditKnowledge);
        }
    });
}
var toaddKnowledge = function () {
    if ($('#knowledgeName').val().trim() == '') {
        showTip("请输入名称!");
    } else {
        //alert('_'+$('#knowledgeName').val()+'_');
        // var noteIds = ['179772ec-3858-11e7-8e4c-e18a12b866d4', 'b80f931c-3858-11e7-8e4c-e18a12b866d4'];
        $.ajax({
            'url': '/memorypalace/knowledge/afteraddknowledgetree.action',
            'type': 'GET',
            'data': 'fatherKnowledgeId=' + $("#knowledgeFatherId").val() + '&' +
            'knowledgeName=' + $("#knowledgeName").val() + '&' +
            'knowledgeType=' + $("#knowledgeType").val() + '&noteIds=' + noteChoosed,
            'success': function () {
                getJsMindData();
                showTip("添加成功", undefined, true);
            }
        });
        // 刷新思维导图的数据
    }
}

var toeditKnowledge = function () {
    console.log("toeditKnowledge");
    var nodeId = $("#knowledgeId").val();
    if ($('#knowledgeName').val().trim() == '') {
        //alert('__'+$('#knowledgeName').val()+'__');
    } else {
        //alert('_'+$('#knowledgeName').val()+'_');
        var noteIds = noteChoosed;

        if ($("#knowledgeFatherId").val().trim().length > 0) {
            $.ajax({
                'url': '/memorypalace/knowledge/aftereditknowledgetree.action',
                'type': 'GET',
                'data': 'knowledgeId=' + nodeId + '&' +
                'fatherKnowledgeId=' + $("#knowledgeFatherId").val() + '&' +
                'knowledgeName=' + $("#knowledgeName").val() + '&' +
                'knowledgeType=' + $("#knowledgeType").val() + '&noteIds=' + noteIds,
                'success': function () {
                    getJsMindData();
                    showTip("编辑成功", undefined, true);
                }
            });
        } else {
            $.ajax({
                'url': '/memorypalace/knowledge/aftereditknowledgetree.action',
                'type': 'GET',
                'data': 'knowledgeId=' + nodeId + '&' +

                'knowledgeName=' + $("#knowledgeName").val() + '&' +
                'knowledgeType=' + $("#knowledgeType").val() + '&noteIds=' + noteIds,
                'success': function () {
                    getJsMindData();
                    showTip("编辑成功", undefined, true);
                }
            });
        }
        // 刷新思维导图的数据
    }
}

// --------------------弹窗结束
// --------------------删除开始
var deleteAllNode = function () {
    // 先删除现有的node
    var nodeIds = [];
    $("jmnode").each(function (i, node) {
        if ($(node).attr("nodeId") != "root" && $(node).attr("nodeId") != undefined) {
            nodeIds.push($(node).attr("nodeId"));
        }
    });
    console.log(nodeIds);
    jm.enable_edit();
    for (var i = 0; i < nodeIds.length; i++) {
        jm.remove_node(nodeIds[i]);
    }
    jm.disable_edit();
}

var deleteKnowledge = function () {
    // 拿到当前需要的删除的nodeId
    var nodeId = $(".selected").attr('nodeId');
    if (nodeId != null) {
        // 当前选中了一个node

        var node = jm.get_node(nodeId);
        var children = node.children;
        console.log(children.length);
        if (node.data.type == 1 &&
            (children.length == 0 ||
                (children.length > 0 && children[0].data.type == 0)
            )
        ) {
            // 发出删除请求
            $.ajax({
                'url': '/memorypalace/knowledge/deleteknowledgetree.action',
                'type': 'GET',
                'data': 'knowledgeId=' + nodeId,
                'success': function () {
                    // 删除node
                    jm.enable_edit();
                    jm.remove_node(nodeId);
                    jm.disable_edit();
                    getJsMindData();
                    showTip("删除成功", undefined, true);
                },
                'error': function () {
                    showTip("删除失败");
                }
            });
        } else {
            if (node.data.type == 1 && children.length > 0) {
                showTip('请先删除子知识体系');
            }
            if (node.data.type == 0) {
                showTip('请选择一个知识体系');
            }
        }

    } else {
        showTip('请选中一个知识体系');
    }
}

// --------------------删除结束
// --------------------错误开始
var showError = function () {
    //错误文字提示
    showTip('My God, 出错啦！！！', 2500, false);
}
var t;
var showTip = function (t1, t2, t3, callback) {
    // 如果没有显示
    t1 = t1 != undefined ? t1 : 'Error...';
    t2 = t2 != undefined ? parseInt(t2) : 2500;
    var tip = '<div class="HTooltip shake animated" style="width:280px;padding:10px;text-align:center;background-color:#D84C31;color:#fff;position:fixed;top:10px;left:50%;z-index:100001;margin-left:-150px;box-shadow:1px 1px 5px #333;-webkit-box-shadow:1px 1px 5px #333;">' + t1 + '</div>';
    if (t3 == true && t3 != undefined) {
        tip = '<div class="HTooltip bounceInDown animated" style="width:280px;padding:10px;text-align:center;background-color:#5cb85c;color:#fff;position:fixed;top:10px;left:50%;z-index:100001;margin-left:-150px;box-shadow:1px 1px 5px #333;-webkit-box-shadow:1px 1px 5px #333;">' + t1 + '</div>';
    }
    $('.HTooltip').remove();
    $('body').stop().append(tip);
    if (t != null) {
        clearTimeout(t);
    }
    t = setTimeout(function () {
        $('.HTooltip').remove();
        if (callback != undefined) {
            methods.fire.call(this, callback);
        } //隐藏后的回调方法
    }, t2);
}

